/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */
import { HvigorLogger } from '../../log/hvigor-log.js';
import { DEFAULT_DAEMON_REGISTRY_PATH } from '../const/daemon-const.js';

import { DaemonCacheService } from './daemon-cache-service.js';
import { DaemonInfo, DaemonState } from './daemon-info.js';

interface DaemonRegistry {
  getIdles(): DaemonInfo[];

  getInfos(): DaemonInfo[];

  getInfo(keyId: string): DaemonInfo | undefined;

  setInfo(keyId: string, daemonInfo: DaemonInfo): void;
}

export class DefaultDaemonRegistry implements DaemonRegistry {
  private _log: HvigorLogger;
  private daemonCacheService: DaemonCacheService;

  constructor(log: HvigorLogger) {
    this._log = log;
    this.daemonCacheService = new DaemonCacheService(DEFAULT_DAEMON_REGISTRY_PATH, log);
  }

  getIdles(): DaemonInfo[] {
    return this.getInfos().filter((daemonInfo) => {
      return daemonInfo.state === DaemonState.IDLE;
    });
  }

  getAlive(): DaemonInfo[] {
    return this.getInfos().filter((daemonInfo) => {
      return daemonInfo.state !== DaemonState.STOPPED && daemonInfo.state !== DaemonState.BROKEN && daemonInfo.state !== DaemonState.BUSY;
    });
  }

  getInfo(keyId: string): DaemonInfo | undefined {
    return {
      ...this.daemonCacheService.get(keyId),
      keyId: keyId,
    };
  }

  getInfos(): DaemonInfo[] {
    return Object.entries(this.daemonCacheService.getAll()).map(([key, daemonInfo]) => {
      return {
        ...daemonInfo,
        keyId: key,
      };
    });
  }

  getDaemonInfoByPid(pid: number): DaemonInfo | undefined {
    return this.getInfos()
      .filter((daemonInfo) => {
        return daemonInfo.pid === pid;
      })
      .pop();
  }

  setInfo(keyId: string, daemonInfo: DaemonInfo): void {
    this.daemonCacheService.set(keyId, daemonInfo);
  }
}
